<template>
  <view>
    <view class="p-32">
      <uv-navbar title="AI" placeholder fixed :autoBack="true"></uv-navbar>
      <u-form labelPosition="top" :model="formData" :rules="rules" ref="uForm" labelWidth="auto">
        <view class="formItem p-x-32 p-y-20 m-b-16" v-for="(item, index) in selectList" :key="index">
          <up-form-item :prop="`formData${item.id}`">
            <view class="">
              <view class="flex-ali font-28 font-weight-middle m-b-30">
                <u-icon :name="ASSETSURL + 'icon3.png'" size="28rpx" :label="item.title + tipList[item.type - 1]"
                  labelSize="28rpx" labelColor="#333"></u-icon>
                <text class="font-32 text-main" v-if="item.is_required == 1">*</text>
              </view>
              <view class="flex-bet-ali m-t-60" v-if="item.type == 4 || item.type == 5">
                <text class="font-28 text-666" v-if="item.type == 4">身高体重选择：</text>
                <text class="font-28 text-666" v-if="item.type == 5">生日选择：</text>
                <u-icon name="arrow-right" color="#8C8C8C" size="24rpx" :label="item.answer || '请选择'" labelPos="left"
                  @click="openPicker(item.type, index)"></u-icon>
              </view>
              <view class="" v-else-if="item.type == 3">
                <input type="text" class="p-24" v-model="item.answer" placeholder="请填写" />
              </view>
              <view class="flex-col" style="row-gap: 16rpx; max-height: 530rpx; overflow-y: auto" v-else>
                <block v-for="(it, indey) in item.options" :key="indey">
                  <view class="tag flex-ali p-24" @click="throttle(handleSelect(index, indey, item, it), 500)"
                    :class="{ cur: it.checked }">
                    {{ it.label }}
                  </view>
                </block>
              </view>
            </view>
          </up-form-item>
        </view>
      </u-form>
      <view class="flex-cen m-y-50">
        <dy-button @click="sure">提交</dy-button>
      </view>
    </view>
    <uv-picker ref="picker" confirmColor="#830102" :columns="dataList" :defaultIndex="defaultIndex" keyName="label"
      @confirm="confirm" @cancel="cancel" @change="changeHandler"></uv-picker>
    <up-datetime-picker confirmColor="#830102" ref="datetimePickerRef" mode="datetime" maxMinute="0" v-model:show="show"
      v-model="monthVal" @cancel="show = false" :minDate="0" :maxDate="dateTimeNum" @confirm="monthConfirm"
      :formatter="formatter"></up-datetime-picker>
    <uv-popup ref="popup" mode="center" :safeAreaInsetBottom="false" round="12rpx">
      <view class="result flex-col-ali p-y-36 p-x-30" style="width: 690rpx">
        <view class="font-32 font-weight-bold">AI定制方案</view>
        <!-- <uv-image :src="ASSETSURL + 'cs1.png'" width="402rpx" height="402rpx"></uv-image> -->
        <view class="m-y-32" style="height: 40vh; overflow-y: auto">
          <block v-for="(item, index) in ai_design" :key="index">
            <view class="text-body font-weight-middles m-b-20" v-if="item">
              {{ index }}
            </view>
            <view class="text-body m-b-30" v-if="Array.isArray(item)">
              <view class="l-h-36" v-for="(it, indey) in item" :key="indey">
                {{ indey + 1 }}、
                <text v-for="(ite, inde) in it" :key="inde">
                  {{ ite }}
                  <text v-if="inde != 0 || inde != '规格'"></text>
                </text>
              </view>
            </view>
            <view class="text-body l-h-36 m-b-30" v-else>
              {{ item }}
            </view>
          </block>
        </view>
        <dy-button width="540rpx" btn_bg="#830102" @click="sub">方案效果预览</dy-button>
        <view class="font-32 font-weight-middle m-t-32" @click="goBack">重新测试</view>
      </view>
    </uv-popup>

    <uv-popup ref="popuplott" mode="center" :closeOnClickOverlay="false" bgColor="transparent"
      :safeAreaInsetBottom="false" round="12rpx">
      <view class="flex-cen-ali-col" v-if="modelVale >= 1" style="width: 500rpx; height: 500rpx;background: transparent;">
        <l-circle size="300rpx" :current="modelVale" :percent="target" strokeWidth="15" trailWidth="15"
          trailColor="#FFF" strokeColor="#830102">
          <text class="text-white font-28">{{ modelVale }}%</text>
        </l-circle>
        <view class="font-28 text-white m-t-30 wave-text">
          <span v-for="(char, i) in waveTextArr" :key="i" :class="{ 'wave-active': i === waveActiveIndex }">{{ char
          }}</span>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script setup>
import { computed, onMounted, ref, onBeforeUnmount } from 'vue';
import { onReady } from '@dcloudio/uni-app';
import { throttle } from '@/uview-plus';
import { CustomizeCenterApi } from '../../api/serves';
const selectList = ref([]);
import { useCounter } from '@/mixins/userHooks';
const { tool } = useCounter();
const dateTimeNum = new Date();
// 响应式数据
const tipList = ref(['（单选）', '（多选）', '', '', '', '（多选）']);
const wrist_reference = ref([]);
const picker = ref(null);
const popuplott = ref(null);
const target = ref(0)
const modelVale = ref(0)
const datetimePickerRef = ref(null);
const popup = ref(null);
const show = ref(false);
const dataList = ref([]);
const selectIndex = ref(0);
const monthVal = ref(946656000000);
const ai_design = ref(null); 
const survey_id = ref(null);
const waveText = 'AI测算中,专属手串值得等待';
const waveTextArr = waveText.split('');
const waveActiveIndex = ref(0);
let waveTimer = null;

const startWave = () => {
  let i = 0;
  waveTimer = setInterval(() => {
    waveActiveIndex.value = i % waveTextArr.length;
    i++;
  }, 120);
};
const stopWave = () => {
  if (waveTimer) clearInterval(waveTimer);
};
onMounted(() => {
  startWave();
});
onBeforeUnmount(() => {
  stopWave();
});

const formData = computed(() => {
  let obj = {};
  selectList.value.forEach((item) => {
    obj[`formData${item.id}`] = null;
  });
  console.log(obj, 'obj');
  return obj;
});
const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`;
  }
  if (type === 'month') {
    return `${value}月`;
  }
  if (type === 'day') {
    return `${value}日`;
  }
  return value;
};
const goBack = () => {
  popup.value.close();
  tool.jump_back();
};

onReady(() => {
  // 微信小程序需要用此写法
  datetimePickerRef.value.setFormatter(formatter);
  // popuplott.value.open();
  // startLoading();
});
const rules = computed(() => {
  return {};
});
onMounted(() => {
  getList();
});
const sub = () => {
  uni.redirectTo({
    url: '/packageDiy/customized/customized?survey_id=' + survey_id.value
  });
};

const openPicker = (e, index) => {
  selectIndex.value = index;

  if (e == 4) {
    picker.value.open();
  } else {
    console.log(e, index);
    show.value = true;
  }
};
const monthConfirm = (e) => {
  console.log(e, '123');
  show.value = false;
  selectList.value[selectIndex.value].answer = tool.formatting(e.value, 'YYYY年MM月DD日 HH时');
};
const cancel = () => {
  picker.value.close();
};
const confirm = (e) => {
  console.log(e, '123123');
  selectList.value[selectIndex.value].answer = e.value[1].wrist_size;
  cancel();
};
// 处理选项选择
const handleSelect = (index, indey, item) => {
  let items = selectList.value[index].options;
  if ((item.type == 1 || (indey == 0 && item.type == 6)) && items[indey].checked) return;
  // 单选模式特殊处理：如果点击已选中项则取消选择
  if (item.type == 1 || (indey == 0 && item.type == 6) ) {
    items.forEach((it, inde) => {
      it.checked = inde == indey;
    });
  } else {
    items[indey].checked = !items[indey].checked;
    if (item.type == 6) {
      items[0].checked = false;
    }
  }
  let arr = [];
  items.map((it) => {
    if (it.checked) arr.push(it.label);
  });
  selectList.value[index].answer = arr.join();
  let obj = items[indey].next_questions || items[indey].next_question || [];
  console.log(obj);
  if (obj.length && items[indey].checked) {
    obj = JSON.parse(JSON.stringify(obj));
    let addArr = selectList.value[index].addId || [];
    addArr = JSON.parse(JSON.stringify(addArr));
    addArr.push(items[indey].value);
    obj.forEach((it, inde) => {
      selectList.value.splice(index + 1 + inde, 0, { addId: addArr, ...it });
    });
    console.log(addArr, 'items[indey].value');
  }
  items.forEach((it, inde) => {
    if (it.checked) return;
    selectList.value = selectList.value.filter((x, y) => !x.addId || !x.addId.includes(it.value));
  });
};

const duration = 25000; // 20秒
let timer = null;

const startLoading = () => {
  modelVale.value = 0;
  target.value = 0; // target也从0开始
  const startTime = Date.now();
  const endValue = 99; // 目标百分比
  if (timer) clearInterval(timer);

  timer = setInterval(() => {
    const elapsed = Date.now() - startTime;
    let percent = Math.min((elapsed / duration) * endValue, endValue);
    modelVale.value = Math.floor(percent);
    target.value = Math.floor(percent); // target同步增长

    if (elapsed >= duration) {
      modelVale.value = endValue;
      target.value = endValue;
      clearInterval(timer);
      // 动画结束后可执行后续逻辑
      // popuplott.value.close();
    }
  }, 50); // 每50ms刷新一次
};
// 提交
const sure = async () => {

  // return
  // 其余逻辑等动画结束后再执行
  // tool.loading('AI分析中');
  let bool = {};
  let answers = selectList.value.map((item) => {
    if (!item.answer && item.is_required == 1) bool = item;
    return {
      question_id: item.id,
      answer: item.answer || ' '
    };
  });
  if (bool.id) return tool.alert(bool.title);
  console.log(answers);
  popuplott.value.open();
  startLoading();
  let { code, data, msg } = await CustomizeCenterApi.saveQuestionAnswer({ answers });
  if (code != 1) return tool.alert(msg);
  console.log(data, '123123');
  clearInterval(timer);
  popuplott.value.close();
  ai_design.value = data.ai_design;
  survey_id.value = data.survey_id;
  popup.value.open();
  tool.loading_h();
};
const changeHandler = ({ indexs }) => {
  console.log(indexs[0], '123');
  dataList.value[1] = wrist_reference.value[indexs[0]].weights;
};
// 获取题目列表
const getList = async () => {
  let { code, data, msg } = await CustomizeCenterApi.getQuestion();
  if (code != 1) return tool.alert(msg);
  selectList.value = data.questions;
  wrist_reference.value = data.wrist_reference;
  dataList.value = [data.wrist_reference, data.wrist_reference[0].weights];
  console.log(dataList.value);
};
</script>
<style>
page {
  background: #f6f6f6;
}
</style>
<style lang="scss" scoped>
.formItem {
  width: 682rpx;
  min-height: 215rpx;
  flex-shrink: 0;
  border-radius: 6rpx;
  background: #fff;
  // linear-gradient(180deg, #fff6f7 0%, #fff 100%)
}

.tag {
  width: 100%;
  height: 70rpx;
  border-radius: 6rpx;
  border: 2rpx solid #cfcfcf;
  color: #999;
  font-feature-settings: 'liga' off, 'clig' off;
  font-family: 'Source Han Sans CN';
  flex-shrink: 0;
}

.cur {
  color: #000;
  border: 2rpx solid #1e1e1e;
}
</style>

<style>
.wave-text {
  display: flex;
  justify-content: center;
  align-items: center;
}

.wave-text span {
  display: inline-block;
  transition: transform 0.2s;
}

.wave-text .wave-active {
  transform: translateY(-6rpx) scale(1.2);
  /* color: #fffbe0; */
}
</style>
